package com.nondo.dean.dealer.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.dean.auth.common.bean.RoleEnum;
import com.nondo.dean.common.constants.ViewType;
import com.nondo.dean.common.tool.AliyunOssTool;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.IPUtil;
import com.nondo.dean.common.tool.RequestUtils;
import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.dealer.domain.CustomerView;
import com.nondo.dean.dealer.domain.Store;
import com.nondo.dean.dealer.domain.StoreExample;
import com.nondo.dean.dealer.domain.StoreProduct;
import com.nondo.dean.dealer.mapper.StoreMapper;
import com.nondo.dean.dealer.model.UserBean;
import com.nondo.dean.dealer.model.result.ProductResult;
import com.nondo.dean.dealer.model.result.StoreProductResult;
import com.nondo.dean.dealer.model.result.StoreResult;

/**
 * @author ken.
 * @version 1.0
 * @email 695093513@qq.com
 * @date 2018/4/24
 */
@Component
public class StoreService {
    
    @Autowired
    AliyunOssTool aliyunOssTool;
    
    @Autowired
    UserService userService;

    @Autowired
    StoreMapper storeMapper;

    @Autowired
    StoreProductService storeProductService;

    @Autowired
    ProductService productService;
    
    @Autowired
    private CustomerViewService customerViewService;

    /**
     * 添加
     *
     * @param store
     * @return
     */
    @Transactional
    public int add(Store store) {
        return this.storeMapper.insertSelective(store);
    }

    /**
     * 更新
     *
     * @param store
     * @return
     */
    @Transactional
    public int update(Store store) {
        return this.storeMapper.updateByPrimaryKeySelective(store);
    }

    /**
     * 删除
     *
     * @param store
     * @return
     */
    public int delete(Store store) {
        store.setDelFlag(Store.DEL_FLAG_DELETE);
        return this.storeMapper.updateByPrimaryKeySelective(store);
    }

    /**
     * 根据主键查询
     *
     * @param id
     * @return
     */
    public Store select(Integer id) {
        return this.storeMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取列表
     *
     * @param offset
     * @param limit
     * @param store
     * @return
     */
    public List<Store> getList(int offset, int limit, Store store) {
        StoreExample example = new StoreExample();
        example.setOrderByClause("create_date DESC");
        RowBounds rowBounds = new RowBounds(offset, limit);
        StoreExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, store);
        return storeMapper.selectByExampleWithRowbounds(example, rowBounds);
    }

    /**
     * 获取不分页的分类列表
     *
     * @param store
     * @return
     */
    public List<Store> getList(Store store) {
        StoreExample example = new StoreExample();
        example.setOrderByClause("create_date DESC");
        StoreExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, store);
        return storeMapper.selectByExample(example);
    }

    /**
     * 数据统计
     *
     * @param store
     * @return
     */
    public Long count(Store store) {
        StoreExample example = new StoreExample();
        StoreExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, store);
        return storeMapper.countByExample(example);
    }

    /**
     * 设置查询条件
     *
     * @param criteria
     * @param store
     */
    void setCriteria(StoreExample.Criteria criteria, Store store) {
        if (store != null) {
            if (store.getId() != null) {
                criteria.andIdEqualTo(store.getId());
            }
            if (StringUtils.isNoneBlank(store.getName())) {
                criteria.andNameEqualTo(store.getName());
            }
        }
        criteria.andDelFlagEqualTo(Store.DEL_FLAG_NORMAL);
    }

    /**
     * 获取APP店铺首页信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public Store index() {
        Store store = new Store();;
        // 1.判断当前经销商用户是否具有店铺
        String userRoles = userService.getLoginUserRoles();
        if (!userRoles.contains(RoleEnum.JXS)) {
            return store;
        }
        String userName = userService.getLoginUserName();
        UserBean user = userService.getUserBeanByName(userName);
        if (user == null || 
            user.getId() == null) {
            return store;
        }
        Integer storeId = user.getStoreId();
        // 2.没有则创建店铺
        if (storeId == null || storeId == 0) {
            //生成店铺
            store.setName(user.getUserName());
            store.setAddress(user.getAddress());
            store.setPhone(user.getMobile());
            storeMapper.insertSelective(store);
            //设置用户店铺
            storeId = store.getId();
            user.setStoreId(storeId);
            userService.update(user);
            //初始化店铺产品
            initStoreProduct(storeId);
        }
        // 3.获取店铺信息
        store = this.storeMapper.selectByPrimaryKey(storeId);
        store.setLogo(aliyunOssTool.getImgUrl(store.getLogo()));
        return store;
    }
    
    /**
     * 初始化店铺产品信息
     * 将平台推荐的产品加入店铺的商品列表
     * @param storeId 店铺ID
     */
    private void initStoreProduct(Integer storeId) {
        List<ProductResult> productList = productService.getRecommandProductList();
        for (ProductResult productResult : productList) {
            StoreProduct storeProduct = new StoreProduct();
            storeProduct.setProductId(productResult.getId());
            storeProduct.setProductCode(productResult.getCode());
            storeProduct.setProductName(productResult.getName());
            storeProduct.setSalePrice(productResult.getSalePrice());
            storeProduct.setStoreId(storeId);
            storeProduct.setShelfStatus(1);
            this.storeProductService.add(storeProduct);
        }
    }

    /**
     * 修改店铺信息
     *
     * @param request
     * @param response
     * @param store 店铺信息
     * @return
     */
    @Transactional
    public Store appUpdate(Store store) {
        String userName = userService.getLoginUserName();
        UserBean user = userService.getUserBeanByName(userName);
        Integer storeId = user.getStoreId();
        if (storeId != null) {
            store.setId(storeId);
            storeMapper.updateByPrimaryKeySelective(store); 
            store.setLogo(aliyunOssTool.getImgUrl(store.getLogo()));
            return store;
        }
        return store;
    }

    /**
     * 经销商店铺预览
     * @return
     */
    public StoreResult userStorePreview(Integer storeId, HttpServletRequest request){
        Store store = select(storeId);
        StoreResult bean = StoreResult.coverToBean(store);
        if(Store.DEL_FLAG_NORMAL.equals(bean.getLatitude()) || Store.DEL_FLAG_NORMAL.equals(bean.getLongitude())){
            Map<String,String> resMap = longitudeAndLatitude(bean.getAddress());
            bean.setLatitude(resMap.get("lat"));
            bean.setLongitude(resMap.get("lng"));
        }
        List<StoreProductResult> newList= new ArrayList<StoreProductResult>();
        List<StoreProduct> storeProductList = storeProductService.getStoreProductListByStoreId(storeId);
        for(StoreProduct storeProduct : storeProductList){
            StoreProductResult result = new StoreProductResult();
            ProductResult productResult = productService.getProductBeanById(storeProduct.getProductId());
            BeanUtils.copy(productResult, result);
            BeanUtils.copy(storeProduct, result);
            result.setId(storeProduct.getProductId());
            result.setMainImage(aliyunOssTool.getImgUrl(productResult.getMainImage()));
            newList.add(result);
        }
        bean.setStoreProductResultList(newList);
        
        // 添加店铺浏览记录
        CustomerView customerView = new CustomerView();
        customerView.setClient(RequestUtils.getClientInfo(request));
        customerView.setUrl(RequestUtils.getRequestUrl(request));
        customerView.setIp(IPUtil.getIpAddress(request));
        customerView.setType(ViewType.SHOP);
        customerView.setGoValue(String.valueOf(storeId));
        customerView.setDescription("店铺名称：" + store.getName());
        customerViewService.add(customerView);
        return bean;
    }

    /**
     * 读取经纬度
     * @param address
     * @return
     */
    public Map<String,String> longitudeAndLatitude(String address) {
        String result="";
        Map<String,String> newMap = new HashMap<>();
        //读取返回结果
        BufferedReader read = null;
        String v_url = "http://api.map.baidu.com/geocoder/v2/?address='"+address+"'&output=json&ak=WP0g4xQNn7PqUUemrQE81Xd324OvKrwR&callback=showLocation";
        try {
            //创建url
            URL realurl = new URL(v_url);
            //打开连接
            URLConnection connection = realurl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //建立连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            read = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;//循环读取
            while ((line = read.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        result = result.substring(27,result.length()-1);
        JSONObject obj = JSON.parseObject(result);
        JSONObject jsonObject =  JSON.parseObject(obj.getString("result"));
        JSONObject localObject =  jsonObject.getJSONObject("location");
        newMap.put("lng",localObject.getString("lng"));
        newMap.put("lat",localObject.getString("lat"));
        return newMap;
    }
}
